# coding=utf-8
from Grapher import *


class MoveToPos(MovableUi):
    def __init__(self, base_ui_control, time):
        # type:(BaseUIControl,float)->None
        self.initialPos = base_ui_control.GetPosition()
        self.totalTime = float(time)
        self.speedX = 0.0
        self.speedY = 0.0
        self.destinationPos = (0, 0)
        self.backFunc = lambda *args: None
        self.args = []
        super(MoveToPos, self).__init__(base_ui_control)

    def ResetInitialPos(self, initialPos=None):
        """
        重置原位置
        :return:
        """
        self.initialPos = self.baseUiControl.GetPosition() if initialPos is None else initialPos

    def Reset(self):
        super(MoveToPos, self).Reset()
        self.baseUiControl.SetPosition(self.initialPos)
        self.backFunc = lambda: None
        self.args = tuple()

    def Finish(self):
        super(MoveToPos, self).Finish()
        self.backFunc(*self.args)
        self.Reset()

    def StartMove(self, destinationPos, backFunc, *backFuncArgs):
        self.destinationPos = destinationPos
        self.args = backFuncArgs
        self.backFunc = backFunc
        dx, dy = destinationPos[0] - self.initialPos[0], destinationPos[1] - self.initialPos[1]
        self.speedX = dx / self.totalTime
        self.speedY = dy / self.totalTime
        super(MoveToPos, self).Start()

    def Refresh(self):
        if self and self.state != ControlState.Run:
            return
        runTime = self.GetWorkTime()
        if runTime < self.totalTime:
            self.baseUiControl.SetPosition((
                self.speedX * runTime + self.initialPos[0], self.speedY * runTime + self.initialPos[1]
            ))
        else:
            self.baseUiControl.SetPosition((
                self.destinationPos[0] + self.initialPos[0], self.destinationPos[1] + self.initialPos[1]
            ))
            self.Finish()
        return runTime
